package com.archermind.boc.dal.business.impl;


import com.archermind.boc.Logger;
import com.archermind.boc.dal.business.service.BizService;

import com.archermind.boc.domain.Biz;
import com.archermind.boc.domain.IQ;
import com.archermind.boc.ehcache.EhcacheInterface;
import com.archermind.boc.ehcache.UserCache;
import com.archermind.boc.ehcache.UserEhcacheImpl;
import com.archermind.boc.ehcache.UserStatus;
import com.archermind.boc.socket.out.Impl.BocSocketWriter;

public class Transmit {
	private static Logger log = Logger.getLogger(Transmit.class.getName());
	
    public static void transmitMedia(String sessionID,IQ iq){
    	String newSessionId=transmitUser(sessionID);
    	iq.setSessionID(newSessionId);
    	
    	BocSocketWriter s = new BocSocketWriter();
		s.write(iq);
    	
    }
    
    /**
     * 根据入参的sessionID 找到与之相对应(想要转发)的 sessionid
     * 如：根据处理bizid为1001的userA 授权sessionID 返回 处理bizid为1001的userB 经办sessionID
     * @param sessionID
     * @return
     */
    public static String transmitUser(String sessionID){
    	EhcacheInterface ei = new UserEhcacheImpl();
    	UserCache uc = ei.getUserCachebySessionId(sessionID);
    	if(uc==null){
    		return "0";
    	}
    	
    	String newID = "0";
    	Biz biz = uc.getBiz();
    	String role = uc.getRole();
    	int userid;
    	
    	BizService bs=new BizService();
    	if(biz ==null){
    		return newID;
    	}
    	Biz bizStub = bs.getBizById(biz.getBizid());
    	
    	if(UserStatus.USER_GRANT.equals(role)){
    		userid = bizStub.getFromBankNum();
    	}else{
    		userid = bizStub.getToBankNum();
    	}
    	
    	
    	UserCache newuc =ei.getUserCacheById(userid);
    	if(newuc!=null){
    		newID= newuc.getSessionID();
    	}else{
    		log.error("cannt find the corresponding user!!!");
    	}
    	return newID;
    }
    
}
